package org.example.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.yc.damai.dto.Result;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.example.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

@Component
public class MyinfoFilter extends ZuulFilter {

    @Autowired
    LoginFilter loginFilter;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return loginFilter.shouldFilter("login/myinfo");
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String loginToken = null;
        Result  result = new Result();
        for (Cookie cookie : request.getCookies()) {
            if(cookie.getName().equals("loginToken")){
                loginToken = cookie.getValue();
            }
        }
        if(loginToken == null){
            result.setCode(0);
            result.setMsg("未登录");
        } else {
            try{
                Claims claims = JwtUtil.parseJWT(loginToken);
                result.setCode(1);
                result.setData(claims);
            } catch (ExpiredJwtException e){
                result.setCode(-1);
                result.setMsg("登录已过期");
                Cookie cookie = new Cookie("loginToken", "");
                cookie.setMaxAge(0);
                cookie.setPath("/");
                context.getResponse().addCookie(cookie);
            }
        }
        try {
            String json = new ObjectMapper().writeValueAsString(result);
            // 阻止请求到达目标资源
            context.setSendZuulResponse(false);
            context.getResponse().setContentType("application/json;charset=utf-8");
            context.setResponseBody(json);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
